<?php
/**
 * Created by PhpStorm.
 * User: 常志明
 * Date: 2018-08-15
 * Time: 11:37
 *
 */

namespace app\index\controller;

class EquipRecord
{
    const equiprecord = [
        'parentId'  => '',  //父id
        'type'      => '',  //专业/系统/设备/子设备
        //...      => '',   //任意多字段
    ];

    public static function getData($where, $one = true, $table = 'equiprecord')
    {
        return ($one == true) ? getFirst(mongo($table)->where($where)->select()) : mongo($table)->where($where)->select();
    }
    public static function setData($where, $data, $table = 'equiprecord')
    {
        mongo($table)->where($where)->update($data);
    }
    public static function insertData($data, $table = 'equiprecord')
    {
        mongo($table)->insert($data);
        return mongo($table)->getLastInsID();
    }
    public static function deleteData($where, $table = 'equiprecord')
    {
        mongo($table)->where($where)->delete();
    }

    /**添加子项
     * @param string $id        上级id  没有为空 顶级id为空
       @param string $name      专业名、系统名、设备名
     * @return array
     */
    public static function addEquipRecord($id = '', $name = '')
    {
        if(!empty($perssion = perssion([LOGIN, SHOP])))   //权限判断
            return $perssion;

        $id    = input('id');
        $name  = input('name');

        $type = self::getData(['id'=>$id])['type']??'';
        switch ($type) {
            case '';
                $lastId = self::insertData(['name'=>$name, 'parentId' =>User::getStoreId(), 'type'=>'专业']);
                break;
            case '专业':
                $lastId = self::insertData(['parentId'=>$id, 'name'=>$name, 'type'=>'系统']);
                break;
            case '系统':
                $updateData = [
                    'parentId'        =>$id,
                    'name'            =>$name,
                    'type'            =>'设备',
                    'number'          =>'0',
                    'instructions'    =>[],   //所有作业指导书
                    'desc'            =>input('desc', ''),
                    'imgs'            =>input('imgs/a', []),
                    'contacts_name'   =>input('contacts_name', ''),
                    'contacts_number' =>input('contacts_number', ''),
                ];
                $lastId = self::insertData($updateData);
                break;
            case '设备':
                $insertData = [
                    'parentId'    =>$id,
                    'type'        =>'子设备',
                    'name'        =>$name,
                    'floor'       =>input('floor', ''),
                    'lacation'    =>input('lacation', ''),
                    'parameter'   =>input('parameter', ''),
                ];
                $lastId = self::insertData($insertData);
                break;
        }
        return RD(SUCCESS, $lastId);
    }

    /**
     *   重命名
     *   @param string $id         专业id/系统id/设备id/子设备
         @param string $name       相应名称
     */
    public static function renameEquipRecord($id  = '', $name = '')
    {
        if(!empty($perssion = perssion([LOGIN, SHOP])))   //权限判断
            return $perssion;
        $id   = input('id');
        $name = input('name');

        self::setData(['id'=>$id], ['name'=>$name]);
        return RD(SUCCESS);
    }
    /**
     * 编辑设备详细信息
        @param string $id          设备id
        @param string $number
     *  @param string $name        设备名字
        @param string $desc
        @param array $imgs         [base64, base64]
        @param string $contacts_number
        @param string $contacts_name
     * @return array
     */
    public static function editEquipRecord($id = '', $name = '', $desc='',$imgs=[], $contacts_name = '', $contacts_number = '')
    {
        if(!empty($perssion = perssion([LOGIN, SHOP])))   //权限判断
            return $perssion;

        $id               = input('id');
        $desc             = input('desc'. '');
        $imgs             = input('imgs/a', []);
        $contacts_name    = input('contacts_name', '');
        $contacts_number  = input('contacts_number'. '');

        $updateData = [
            'number'          =>'0',
            'desc'            =>$desc,
            'imgs'            =>$imgs,
            'contacts_name'   =>$contacts_name,
            'contacts_number' =>$contacts_number,
        ];

        self::setData(['id'=>$id], $updateData);
        return RD(SUCCESS, $updateData);
    }
    /**编辑子设备
     * @param string $id         子设备id
     * @param string $name     设备号
     * @param string $lacation   设备位置
     * @param string $parameter  设备参数
     */
    public static function editChildDevice($id = '', $name = '', $lacation = '', $parameter = '')
    {
        if(!empty($perssion = perssion([LOGIN, SHOP])))   //权限判断
            return $perssion;
        $id       = input('id');
        $name     = input('name');
        $lacation = input('lacation');
        $parameter= input('parameter');
        if(empty($id))
            return RD(PARA_NOT_NULL);
        $insertData = [
            'name'        =>$name,
            'lacation'    =>$lacation,
            'parameter'   =>$parameter,
        ];
        self::setData(['id'=>$id], $insertData);
        return RD(SUCCESS);
    }
    /**
     * 获取设备详细  设备  或 子设备
     * @param null $pid  设备id
     * @return array
     */
    public static  function getEquipRecord($id = null)
    {
        if(!empty($perssion = perssion([LOGIN, SHOP])))   //权限判断
            return $perssion;

        $id = input('id');
        if(empty($id))
            return RD(PARA_NOT_NULL);

        $result = self::getData(['id'=>$id]);
        DArray($result, 'parentId');  //删除parentId
        return RD(SUCCESS, $result);
    }
    /**删除数据
     * @param string $id  专业id/系统id/设备id/子设备id
     */
    public static function deleteEquipRecord($id = '')
    {
        if(!empty($perssion = perssion([LOGIN, SHOP])))   //权限判断
            return $perssion;

        $id = empty($id) ? input('id') : $id;

        $result = self::getData(['id'=>$id]);  //本条数据
        if(($result['type'] ?? '') == '设备') {
            EquipRecord::deleteData(['id'=>$result['id']]);                    //删除设备
            Maintenance::deleteData(['deviceId'=>$result['id']]);              //删除维保计划
            JobCard::deleteData(['deviceId'=>$result['id']]);                  //删除作业单
        }

        self::deleteData(['id'=>$id]);  //delete
        $childs = self::getData(['parentId'=>$id], false);
        foreach ($childs as $child) {
            self::deleteEquipRecord($child['id']);  //删除子项
        }
        return RD(SUCCESS);
    }
    //删除门店
    public static function deleteByStore($storeId)
    {
        self::deleteEquipRecord($storeId);                    //删除所有专业
    }
    /**
     * 获取设备档案 树形列表
     * @param string $id
     * @param int $level
     */
    public static function mGetDeviceTreeList($id, $level = 1)  //内部
    {
        $data   = [];
        $result = self::getData(['parentId'=>$id], false);
        foreach ($result as $key=>$value) {
            $child = [];
            if($level - 1 > 0) {
                $child = self::mGetDeviceTreeList($value['id'], $level -1);
            }
            if($value['type'] == '设备') {
                array_push($data, ['id'=>$value['id'], 'name'=>$value['name'], 'imgs'=>$value['imgs'][0]??'', 'children'=>$child]);
                continue;
            }
            array_push($data, ['id'=>$value['id'], 'name'=>$value['name'], 'children'=>$child]);
        }
        return $data;
    }
    public static function getDeviceTreeList($id = '', $level = 1)
    {
        if(!empty($perssion = perssion([LOGIN, SHOP])))   //权限判断
            return $perssion;

        $id      = empty(input('id')) ? User::getStoreId() :input('id');
        $level   = input('level');
        $data    = self::mGetDeviceTreeList($id, $level);
        $devices = [];

        self::getDevicesByType($id, '设备', $devices);  //获取第一个设备id
        $firstId = $devices[0]['id'] ?? '';

        return RD(SUCCESS, ['firstId'=>$firstId, 'data'=>$data]);
    }
    /**获取所有设备信息
     * @param string $id  顶级id
     * @param $type
     * @param $data
     */
    public static function getDevicesByType($id, $type , &$data) //内部
    {
        $result = self::getData(['parentId'=>$id], false);
        foreach ($result as $key=>$value) {
            if($value['type'] == $type) {
                array_push($data, $value);
            } else {
                self::getDevicesByType($value['id'], $type, $data);
            }
        }
    }
    /**获取所有子设备
     * @param string $id  设备id
     * @return array
     */
    public static function getChildDevices($id = '')
    {
        if(!empty($perssion = perssion([LOGIN, SHOP])))   //权限判断
            return $perssion;
        $id  = input('id');
        $childDevices = [];
        self::getDevicesByType($id, '子设备', $childDevices);

        $returnData = [];

        foreach (Store::getFloors()['data'] as $floor) {
            $floorDevice = [];
            foreach ($childDevices as $device) {
                if($device['floor'] == $floor) {
                    array_push($floorDevice, $device);
                }
            }
            array_push($returnData, ['floor'=>$floor, 'device'=>$floorDevice]);
        }
        return RD(SUCCESS, $returnData);
    }
    /**
     * 获取所有二维码
     * @param string $id          id
     * @param string $currentPage 当前页
     * @param string $pageSize    页大小
     * @return array
     */
    public static function getAllQRCode($id = '', $currentPage = null, $pageSize = null)
    {
        if(!empty($perssion = perssion([LOGIN, SHOP])))   //权限判断
            return $perssion;
        $id   = input('id');
        $currentPage  = input('currentPage');
        $pageSize     = input('pageSize');

        $deviceName = self::getData(['id'=>$id])['name'] ?? ''; //设备名字
        //获取所有子设备
        $childdevices = [];
        self::getDevicesByType($id, '子设备', $childdevices);

        foreach ($childdevices as $key=>$device) {
            $childdevices[$key]['deviceName'] = $deviceName;
        }
        $count = count($childdevices);
        array_paging($childdevices, ($currentPage - 1) * $pageSize, $pageSize);
        return RD(SUCCESS,['total'=>$count, 'data'=>$childdevices]);
    }
    //获取所有专业
    public static function getAllMajor()
    {
        if(!empty($perssion = perssion([LOGIN, SHOP])))   //权限判断
            return $perssion;

        $data = [];
        self::getDevicesByType(User::getStoreId(), '专业', $data);
        foreach ($data as $key=>$value) {
            renameArray($data[$key], 'name', 'majorName');
        }
        return RD(SUCCESS, $data);
    }

    /**上传作业指导书
     * @param string $id        设备id
     * @param string $fileName  文件名
     * @return array
     */
    public static function uploadInstruction($id = '', $fileName = '')
    {
        if(!empty($perssion = perssion([LOGIN, SHOP])))   //权限判断
            return $perssion;

        $id       = input('id');
        $fileName = input('fileName', '');
        if(empty($id) || empty($fileName))
            return RD(PARA_NOT_NULL);

        $instructions = self::getData(['id'=>$id])['instructions'] ?? [];
        $path = uploadFileIn();   //获上传路径
        if(empty($path)) {
            return RD(FAIL, '文件格式不对');
        }
        array_push($instructions, ['fileName'=>$fileName, 'path'=>$path]);
        self::setData(['id'=>$id], ['instructions'=>$instructions]);
        return RD(SUCCESS, $path);
    }
    /**删除作业指导书
     * @param string $id    设备id
     * @param string $path  作业指导书路径
     * @return array
     */
    public static function deleteInstruction($id = '', $path = '')
    {
        if(!empty($perssion = perssion([LOGIN, SHOP])))   //权限判断
            return $perssion;
        $id   = input('id');
        $path = input('path');
        if(empty($id) || empty($path))
            return RD(PARA_NOT_NULL);

        $instructions = self::getData(['id'=>$id])['instructions'] ?? [];
        foreach ($instructions as $key=>$instruction) {
            if($instruction['path'] == $path) {
                unset($instructions[$key]);
                break;
            }
        }
        $instructions = array_merge($instructions);
        self::setData(['id'=>$id], ['instructions'=>$instructions]); //删除数据库
        deleteFileIn($path);        //删除文件
        return RD(SUCCESS);
    }
}